<!--
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-05-25 18:13:35
 * @LastEditTime : 2023-05-25 18:22:33
-->
<script lang="ts" setup name="IkNumberDuration">
import { onMounted, ref } from 'vue'
const props = defineProps({
  value: {
    type: Number,
    required: true
  },
  duration: {
    type: Number,
    default: 500
  },
  fix: {
    type: Number,
    default: 0
  }
})

const currentValue = ref(0)

const animateValue = (start: number, end: number) => {
  const duration = props.duration
  let startTime: number
  const update = (currentTime: number) => {
    if (!startTime)
      startTime = currentTime
    const progress = Math.min((currentTime - startTime) / duration, 1)
    currentValue.value = start + progress * (end - start)
    if (progress < 1)
      requestAnimationFrame(update)
  }
  requestAnimationFrame(update)
}

watch(() => props.value, val => {
  animateValue(currentValue.value, val)
})

onMounted(() => {
  animateValue(currentValue.value, props.value)
})
</script>

<template>
  <div class="number-scroll">
    <div class="number">{{ currentValue.toFixed(props.fix) }}</div>
  </div>
</template>

<style scoped>
.number-scroll {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
